from rest_framework.viewsets import ModelViewSet
from rest_framework.mixins import ListModelMixin
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.decorators import action
import pandas as pd
from .models import *
from .serializers import *

# Create your views here.
class SchoolViewset(ModelViewSet):
    queryset = School.objects.all()
    serializer_class = SchoolSerializers

    @action(methods=['post',],detail=False)
    def importSchool(self,request,*args,**kwargs):
        # 接受前端传来的文件
        rev_file = request.FILES.get('file')
        # 判断文件是否为空
        if not rev_file:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 数据处理
        data = pd.read_excel(rev_file,sheet_name=0,header=1,names=['name','mark','longitude',
            'latitude','create_date','address','organizers','credit_code','school_type','disable'])
        data = data.fillna('')
        data.loc[data['disable']=='否','disable'] = False
        data.loc[data['disable']=='是','disable'] = True
        # pd.to_datetime(data['create_date'],format="yyyy-mm-dd")
        # print(data['create_date'],pd.to_datetime(data['create_date'],format="yyyy-mm-dd"))
        row_len = len(data)
        if row_len == 0:
            return Response({'status':False,'error':'你没有输入数据！'})
        else:
            errors = []
            for i in range(row_len):
                try:
                    School.objects.get(name=data.iloc[i]['name'])
                except Exception:
                    School.objects.create(**data.iloc[i])
        return Response({'status':True,'data':'数据导入成功','errors':errors})

class GradeViewset(ModelViewSet):
    queryset = Grade.objects.all()
    serializer_class = GradeSerializers

class ClassBjViewset(ModelViewSet):
    queryset = ClassBj.objects.all()
    serializer_class = ClassBjSerializers

class SubjectViewset(ModelViewSet):
    queryset = Subject.objects.all()
    serializer_class = SubjectSerializers

class NationViewset(ModelViewSet):
    queryset = Nation.objects.all()
    serializer_class = NationSerializers

class PoliticalClimateViewset(ModelViewSet):
    queryset = PoliticalClimate.objects.all()
    serializer_class = PoliticalClimateSerializers